package dgo.interval;

public class Loop extends Interval {
    private Interval _interval;
    private int _loopCount = -1;
    public Loop(int loopCount, Interval interval){
      if(interval.duration == 0) System.out.println("Error[Interval.Loop]:Infinite Loop");
      _interval = interval;
      _loopCount = loopCount;
      if(_loopCount == -1){
        this.duration = -1;
      }else{
        this.duration = _interval.duration * _loopCount;
      }
      
    }

    private void initNode(IntervalNode node){
      node.nodes.addElement(new IntervalNode(this));
    }

    public boolean call(IntervalNode node){
      if(_loopCount == 0) return false;
      
      if(node.nodes.isEmpty()) this.initNode(node);
      
      int d;
      if(this.duration == -1){
        d = node.parent.duration;
      }else{
        d = this.duration;
      }
      
      // Quit if loop finished
      if(d > -1 && node.counter >= d) return false;
      
      while(true){
        if(_interval.call((IntervalNode)node.nodes.elementAt(0))){
          node.counter++;
          return true;
        }else{
          // Init node for Loop
          node.nodes.setElementAt(new IntervalNode(this), 0);
        }
      }
    }
    
}
